package com.foreveross.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * 节点信息属性文件工具类
 * @author luofangyi
 *
 */
public class NodeInfoPropertyUtil {

	private static final String fileName= "nodeInfo.properties";
	
	public static final String NODE_NAME = "node.name";
	public static final String NODE_SN = "node.sn";
	public static final String NODE_UPLOAD_MAX_SIZE = "node.upload.max.size";
	
	public static final String path = NodeInfoPropertyUtil.class.getClassLoader().getResource(fileName).getFile();
	
	private static Properties props = new Properties();
	
	private static Logger logger = Logger.getLogger(NodeInfoPropertyUtil.class);
	
	/**
	 * 根据key获取属性值
	 * @param key
	 * @return
	 */
	public static String getValueByProperty(String key){
		
		synchronized (NodeInfoPropertyUtil.class) {
			InputStream in = null;
			try {
				in = new BufferedInputStream(new FileInputStream(path));
				props.load(in);
				
				String value = props.getProperty(key);
				return value;
			} catch (Exception e) {
				logger.error(e.getMessage());
				return null;
			} finally {
				if(in != null){
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	/**
	 * 根据key获取属性值 —— 带默认值
	 * @param key
	 * @param defalutValue
	 * @return
	 */
	public static String getValueByProperty(String key, String defalutValue){

		return getValueByProperty(key) != null ? getValueByProperty(key) : defalutValue;
	}
	
	/**
	 * 写入key-value到属性文件
	 * @param key
	 * @param value
	 */
	public static void writeProperty(String key, String value){
		synchronized (NodeInfoPropertyUtil.class) {
			InputStream in = null;
			OutputStream fos = null;
			try {
				fos = new FileOutputStream(path);
				in = new BufferedInputStream(new FileInputStream(path));
				props.load(in);
				props.setProperty(key, value);
				// 以适合使用 load 方法加载到 Properties 表中的格式，
				// 将此 Properties 表中的属性列表（键和元素对）写入输出流
				props.store(fos, "Update value");
			} catch (IOException e) {
				logger.error("属性文件更新错误: " + e.getMessage());
			} finally {
				if(in != null){
					try {
						in.close();
					} catch (IOException e) {
						logger.error(e.getMessage());
					}
				}
				if(fos != null){
					try {
						fos.close();
					} catch (IOException e) {
						logger.error(e.getMessage());
					}
				}
			}
        }
	}
	
}
